package cn.chenlh.fx.component;

import cn.chenlh.fx.pojo.ListItem;
import javafx.collections.ObservableList;
import javafx.scene.control.ComboBox;
import javafx.util.StringConverter;

import java.util.function.Consumer;

public class Select<V, T extends ListItem<V>> extends ComboBox<T> {
    ObservableList<T> items;
    private final StringConverter<T> stringConverter = new StringConverter<>() {
        @Override
        public String toString(T object) {
            if (object == null) {
                return "";
            }
            return object.getLabel();
        }

        @Override
        public T fromString(String label) {
            for (T item : items) {
                if (item.getLabel().equals(label)) {
                    return item;
                }
            }
            return null;
        }
    };

    public Select(ObservableList<T> items) {
        super(items);
        setConverter(stringConverter);
    }

    public void onSelect(Consumer<V> consumer) {
        this.setOnAction(e -> {
            T value = Select.this.getValue();
            V data = value.getData();
            consumer.accept(data);
        });
    }

}
